package com.mmall.concurrency.example.aqs;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.mmall.concurrency.example.atomic.AtomicExample3;

@Slf4j
public class CountDownLatchExample1 {
	private static Logger log = LoggerFactory.getLogger(AtomicExample3.class);

    private static int threadCount = 200;

    public static void main(String[] args) throws Exception{
        ExecutorService executorService = Executors.newCachedThreadPool();

        final CountDownLatch countDownLatch = new CountDownLatch(threadCount);

        for (int i = 0; i < threadCount; i++) {
            final int threadNumber = i;
            executorService.execute(()->{
                try{
                    test(threadNumber);
                }catch (Exception e){
                    log.error("exception", e);
                }finally {
                    countDownLatch.countDown(); // 还可以放在你自己的条件中
                }
            });
        }
        countDownLatch.await();
        log.info("finish");
        executorService.shutdown(); // 如果线程池不再使用，不要忘记关闭
    }

    private static void test(int threadNumber) throws Exception{
        Thread.sleep(100);
        log.info("{}", threadNumber);
        Thread.sleep(100);
    }
}
